package Gear;

import GearCommands.GearHashCommand;

import java.util.Scanner;

/**
 * Principal class.
 * Contains useful console operations.
 *
 * @author Davi Mendes
 */
public class Gear {

    /**
     * Console pointer.
     */
    private static final String DP = ">>>";

    /**
     * Console scanner.
     */
    private static final Scanner input = new Scanner(System.in);

    /**
     * Determine if the console is running.
     */
    private boolean run;

    /**
     * Hash to execute commands.
     */
    private final GearHashCommand commands;


    /**
     * Gear constructor.
     */
    private Gear() {
        this.run = true;
        this.commands = new GearHashCommand();

        Factory.initFactory();
    }

    /**
     * Format command and get its arguments.
     *
     * @param commandLine Command to execute.
     *
     * @return Split command.
     */
    public String[] formatCommand(String commandLine) {

        String[] command = commandLine.split("\"");

        if (command.length == 1) {
            command = command[0].split(" ");
        }

        for (int i = 0; i < command.length; i++) {
            command[i] = command[i].trim();
        }

        return command;
    }

    /**
     * Execute formatted command.
     *
     * @param command Formatted command.
     */
    private void parseComand(String[] command) {
        try {
            this.commands.get(command[0]).execute(command, this);
        } catch (NullPointerException ex) {
            System.out.println("Invalid command");
        }
    }

    /**
     * Main method to execute.
     *
     * @param args no arguments accepted.
     */
    public static void main(String[] args) {
        String cmd;
        Gear gear = new Gear();

        System.out.println("------------------ Gear file manipulator ------------------");
        System.out.println("- Davi Diorio Mendes\t\tddioriomendes@gmail.com");
        System.out.println("- Rodrigo Marints Racanicci\tdiguo.m@gmail.com");
        System.out.println("-----------------------------------------------------------");
        System.out.println("");

        while (gear.run) {
            System.out.print(DP + " ");
            cmd = input.nextLine();
            long dt = System.currentTimeMillis();
            gear.parseComand(gear.formatCommand(cmd));
            dt = System.currentTimeMillis() - dt;
            System.out.println(cmd + " done in " + dt + " ms.");
        }

        System.exit(0);
    }

    /**
     * Once exit, set not running.
     */
    public void exit() {
        this.run = false;
    }
}
